package com.xiaotu.utils;


import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author 张晓
 * @create 2021-07-29 21:38
 */
@Slf4j
public class Word2PdfUtil {

    public static void main(String[] args) {
        String docPath = "E:\\360MoveData\\Users\\Administrator\\Desktop\\2-文化产业园区申报申请表.docx";
        String pdfPath = "E:\\360MoveData\\Users\\Administrator\\Desktop\\3-文化产业园区申报申请表.pdf";
        doc2pdf2(new File(docPath), new File(pdfPath));
    }


    /**
     * doc转pdf（程序启动openoffice）
     *
     * @param inputFile  输入文件
     * @param outputFile 输出文件
     * @return
     */
    public static boolean doc2pdf2(File inputFile, File outputFile) {
        long old = System.currentTimeMillis();
        boolean result = false;
        // OpenOffice的安装目录
        String OpenOffice_HOME = "D:/OpenOffice4";
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
            OpenOffice_HOME += "/";
        }
        Process process = null;
        try {
            // 启动OpenOffice的服务
            String command = OpenOffice_HOME
                    + "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
            process = Runtime.getRuntime().exec(command);
            // 连接 OpenOffice实例，运行在8100端口
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
            connection.connect();

            // 转换
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, outputFile);

            // 关闭连接
            connection.disconnect();
            // 销毁OpenOffice服务的进程
            process.destroy();

            log.info("****pdf转换成功，PDF输出：" + outputFile.getPath() + "****");
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            log.error("pdf转换失败", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

}
